//
//  BRLoginViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/10.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRLoginViewController.h"
#import "AppDelegate.h"
#import "BRAreaViewController.h"
#import "GXJWebViewController.h"
#import "BRWelcomeVC.h"
#import <AuthenticationServices/AuthenticationServices.h>

@import GoogleSignIn;
@import FirebaseCore;

@interface BRLoginViewController ()<QMUITextFieldDelegate,ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding>
{

    QMUITextField *_phoneTF;
    QMUITextField *_emailTF;
    QMUITextField *_OtpTF;
    QMUIButton *_areaBtn;
    QMUIButton *_otpBtn;
    NSString *_oldOtp;
    
    UIButton *_biometyBtn;
}

@property (nonatomic,strong) QMUILabel *titleL;

@property (nonatomic,copy) NSString *otpTimeKey;

@property (nonatomic,strong) BRWelcomeVC *welcomeVC;

@end

@implementation BRLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _oldOtp = @"";
    
    // 修复：启用 UI 设置
    [self setUI];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
    
    NSInteger time = [BrezzeTimeManage getimeIntervalBy:self.otpTimeKey wirhMax:kTimeMax];
    if (time == 0) {
       // 则继续计时
        
    }
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationDoit) name:APPTIMEINFORMATION object:nil];
    
    
    [self biometyBtnShow]; //face登录
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self.view endEditing:YES];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - request --
- (void)loginRequet:(NSDictionary *)params {
    
    [BRHud showInView:self.view];
    [[BRRequestManager shared] POST:[BRAPI login] params:params succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        [GGFaceIdManManage shareManage].needSave = NO;
        NSLog(@"%@",dataDict);
        [self br_loginDataConfig:dataDict];
        
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
    }];
}

/// 手机号登录请求（使用表单格式）
- (void)loginRequetWithFormData:(NSDictionary *)params {
    
    [BRHud showInView:self.view];
    [[BRRequestManager shared] POSTWithFormData:[BRAPI mobileLogin] params:params succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        [GGFaceIdManManage shareManage].needSave = NO;
        NSLog(@"%@",dataDict);
        [self br_loginDataConfig:dataDict];
        
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
    }];
}

- (void)requstInTenant:(NSString *)platformId {
    
    NSDictionary *prams = @{@"platformId":platformId,@"qrUrl":@"",@"sno":@""};
    [BRUserManager  loginPlatformRequest:prams succ:^{
        [BRHud hiddenInView:self.view];
        
        [BRUserManager requestUserInfo:^{
            
        } faile:^{
            
        }];
        
        USERManager.isLogin = YES;
        
        AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [app didInitWindow];
        
    } faile:^{
        USERManager.isLogin = NO;
        [BRHud hiddenInView:self.view];
        
    }];
}

- (void)requestInFace {
    NSString *token = GGFaceIdManManage.gg_token;
    if (token.length == 0) {
        
        [BRHud showAuto:@"Failed" inView:self.view];
        NSLog(@"token 失效【%@】",token);
        return;
    }
    [BRHud showInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@?token=%@",[BRAPI faceIDLogin],token];
    [[BRRequestManager shared] POST:url params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {

        [GGFaceIdManManage shareManage].needSave = YES;
        NSLog(@"%@",dataDict);
        [self br_loginDataConfig:dataDict];

    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
        if (code == 10401 || code == 21333) {
            [BRHud showAuto:Localized(@"Set_biometry_expired") inView:self.view];
            [GGFaceIdManManage gg_removeCache];
            [self biometyBtnShow];
        }
        USERManager.isLogin = NO;
    }];
}

- (void)br_loginDataConfig:(NSDictionary *)dataDict {
    NSLog(@"🎉 登录成功，开始配置用户数据...");
    
    // 新接口返回格式：{"code":200,"type":0,"data":{"userId":10001242,"mobile":"866047796","nickName":"hhhh",...},"msg":"OK"}
    NSDictionary *data = dataDict[@"data"];
    if (data && [data isKindOfClass:[NSDictionary class]]) {
        // 保存用户基本信息
        if (data[@"userId"]) {
            NSString *userId = [NSString stringWithFormat:@"%@", data[@"userId"]];
            // 可以保存到 USERManager 的 userModel 中
        }
        
        // 保存手机号等信息
        if (data[@"mobile"]) {
            USERManager.loginPhone = data[@"mobile"];
        }
    }
    
    // 保存token和登录状态（如果新接口有token的话，否则可能通过Cookie管理）
    if (dataDict[@"data"][@"token"]) {
        USERManager.token = dataDict[@"data"][@"token"];
    }
    USERManager.isLogin = YES;
    
    // 保存登录信息以便下次自动填充
    if (_phoneTF.text.length > 0 && !USERManager.loginPhone) {
        USERManager.loginPhone = _phoneTF.text;
    }
    if (_areaBtn.titleLabel.text.length > 0) {
        USERManager.loginCode = [_areaBtn.titleLabel.text stringByReplacingOccurrencesOfString:@"+" withString:@""];
    }
    
    [BrezzeTimeManage removeObjectKey:self.otpTimeKey];
    
    // 登录成功后获取用户详细信息
    NSLog(@"✅ 登录数据配置完成，开始获取用户详细信息...");
    [BRUserManager requestUserCenterInfo:^{
        NSLog(@"✅ 用户详细信息获取成功");
        // 跳转到主界面
        dispatch_async(dispatch_get_main_queue(), ^{
            [BRHud hiddenInView:self.view];
            AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            [app didInitWindow];
        });
    } faile:^{
        NSLog(@"⚠️ 用户详细信息获取失败，但登录成功，继续跳转");
        // 即使获取用户信息失败，也跳转到主界面
        dispatch_async(dispatch_get_main_queue(), ^{
            [BRHud hiddenInView:self.view];
            AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            [app didInitWindow];
        });
    }];
}


#pragma mark - ACTION --
- (void)biometyBtnShow {
    BOOL isShow = [GGFaceIdManManage gg_showBtn];
    UIButton *loginBtn = _biometyBtn;
    loginBtn.hidden = !isShow;
    [GGFaceIdManManage gg_checkFaceAction:^{

    } faile:^(NSInteger code) {
        // 单独处理被锁定后隐藏
        if (@available(iOS 11.0, *)) {
            if (code == LAErrorBiometryLockout) {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                    loginBtn.hidden = YES;
                }];

            }
        }
    }];
}

- (void)clickLoginStatus:(NSInteger)tag {
    
   
    self.loginStatus = tag == 0 ? BRLogin_phone : BRLogin_Email;
    
    NSString *nowOtp = _OtpTF.text;
    _OtpTF.text = _oldOtp;
    _oldOtp = nowOtp;
    
   
}

- (void)setLoginStatus:(BRLOGIN_STAUS)loginStatus {
    _loginStatus = loginStatus;
    _phoneTF.hidden = loginStatus != BRLogin_phone;
   
    _otpBtn.enabled = YES;
    [_otpBtn setTitle:Localized(@"login_get") forState:(UIControlStateNormal)];
    _emailTF.hidden = !_phoneTF.hidden;
}


- (UIFont *)changSelect:(BOOL)selected {
    return selected == YES ?[UIFont fontB:14] :[UIFont fontS:14];
}

- (void)getAreaNum {
    
    [self.view endEditing:YES];
    
    BRAreaViewController *vc = [[BRAreaViewController alloc] init];
    vc.isLogin = YES;
    [self.navigationController pushViewController:vc animated:YES];
//    WS(weakSelf);
    vc.selectCodeBlock = ^(NSInteger code) {
        [self->_areaBtn setTitle:[NSString stringWithFormat:@"+%ld",code] forState:UIControlStateNormal];
    };
}

- (void)longin  {
    [self.view endEditing:YES];
    
    
    NSString *codeStr = @"";
    if (self.loginStatus == BRLogin_phone) {
        
        if ([_areaBtn.titleLabel.text isEqualToString:@"+  "]) {
            [BRHud show:Localized(@"toast_validCode") inView:self.view];
            
            return;
        }
        
        if (_phoneTF.text.length == 0) {
            
            [BRHud show:Localized(@"toast_requiredPhone") inView:self.view];
            return;
        }
        if (![BRTools checkPhone:_phoneTF.text]) {
            
            [BRHud show:Localized(@"toast_validPhone") inView:self.view];
            
            return;
        }
        
        codeStr = [_areaBtn.titleLabel.text substringFromIndex:1];
        // 用于获取 验证码定时器 比对是否同一手机号
        [BRUserManager share].loginCode = codeStr;
        [BRUserManager share].loginPhone = _phoneTF.text;
        
        [BRUserManager share].loginType = 0;
        
    }else {
        // 暂时注释掉邮箱登录功能
        /*
        if (_emailTF.text.length == 0) {
            [BRHud show:Localized(@"toast_requiredEmail") inView:self.view];
            return;
        }
        if (![BRTools checkEmail:_emailTF.text]) {
            
            [BRHud show:Localized(@"toast_validEmail") inView:self.view];
            
            return;
        }
        
        [BRUserManager share].loginEmail = _emailTF.text;
        
        [BRUserManager share].loginType = 1;
        */
    }
    
    if (![BRTools checkOTPCode:_OtpTF.text]) {
        NSString *errStr = _OtpTF.text.length == 0 ? Localized(@"toast_requiredCode") : Localized(@"toast_validCode");
        [BRHud show:errStr inView:self.view];
        
        return;
    }
    
    
    // 新接口：手机号登录使用新接口和参数格式
    if (self.loginStatus == BRLogin_phone) {
        NSDictionary *loginParm = @{
            @"countryCode": codeStr,
            @"phoneNumber": _phoneTF.text,
            @"securityCode": _OtpTF.text
        };
        [self loginRequetWithFormData:loginParm];
    } else {
        // 邮箱登录保留旧接口
        NSMutableDictionary *loginParm = [NSMutableDictionary dictionaryWithDictionary:[self longinParams]];
        loginParm[@"msgCode"] = _OtpTF.text;
        // 暂时注释掉邮箱登录参数
        /*
        loginParm[@"email"] = _emailTF.text;
        loginParm[@"loginType"] = @6;
        */
        [self loginRequet:loginParm];
    }
    
    
}

- (NSDictionary *)longinParams {
    // 登录方式：0-验证码登录 1-Facebook登录 2-Google登录 3-Apple登录 4-微信 5-支付宝
    return @{@"code":@"",
             @"loginType":@0,
             @"phone":@"",
             @"msgCode":@"",
             @"source":@1,
             @"email":@"",
             @"icon":@"",
             @"nickname" : @"",
             @"loginMsg":@""
           };
}

- (void)sendOtpClick:(QMUIButton *)btn {

    if (self.loginStatus == BRLogin_phone) {
        
        if ([_areaBtn.titleLabel.text isEqualToString:@"+  "]) {
            [BRHud show:Localized(@"toast_validCode") inView:self.view];
            
            return;
        }
        
        if (_phoneTF.text.length == 0) {
            
            [BRHud show:Localized(@"toast_requiredPhone") inView:self.view];
            return;
        }
        if (![BRTools checkPhone:_phoneTF.text]) {
            
            [BRHud show:Localized(@"toast_validPhone") inView:self.view];
            
            return;
        }
        
    }else {
        // 暂时注释掉邮箱验证功能
        /*
        if (_emailTF.text.length == 0) {
            [BRHud show:Localized(@"toast_requiredEmail") inView:self.view];
            return;
        }
        if (![BRTools checkEmail:_emailTF.text]) {
            
            [BRHud show:Localized(@"toast_validEmail") inView:self.view];
            
            return;
        }
        */
    }
    
    
    [self.view endEditing:YES];

    [self iGetCode];
}

- (void)iGetCode {
    
    
    [BRHud showHud];
    
    // 新接口：使用表单格式 POST 请求
    if (self.loginStatus == BRLogin_phone) {
        NSString *countryCode = [_areaBtn.titleLabel.text substringFromIndex:1];
        NSString *phoneNumber = _phoneTF.text;
        
        // 新接口参数格式：countryCode, phoneNumber
        NSDictionary *dic = @{
            @"countryCode": countryCode,
            @"phoneNumber": phoneNumber
        };
        
        [[BRRequestManager shared] POSTWithFormData:[BRAPI sendMobileLoginCode] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
            [BrezzeTimeManage share].loginCode = countryCode;
            [BrezzeTimeManage share].loginPhone = phoneNumber;
            
            [BrezzeTimeManage addObjectIndateDic:self.otpTimeKey];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationDoit) name:APPTIMEINFORMATION object:nil];
            [BRHud hidden];
            
        } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
            [BRHud hidden];
            if (code == 21012) {
                if (errMsg.length > 0) {
                    [BRHud showTips:errMsg];
                }
            }
        }];
    } else {
        // 邮箱验证码（保留旧接口）
        NSString *codeStr = [_areaBtn.titleLabel.text substringFromIndex:1];
        NSDictionary *dic = @{@"email":_emailTF.text,@"scene":@1};
        
        [[BRRequestManager shared] GET:[BRAPI verificationCode] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
            [BrezzeTimeManage share].loginEmail = self->_emailTF.text;
            
            [BrezzeTimeManage addObjectIndateDic:self.otpTimeKey];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationDoit) name:APPTIMEINFORMATION object:nil];
            [BRHud hidden];
            
        } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
            [BRHud hidden];
            if (code == 21012) {
                if (errMsg.length > 0) {
                    [BRHud showTips:errMsg];
                }
            }
        }];
    }
}


- (NSString *)otpTimeKey {
    return self.loginStatus == BRLogin_phone ?  BRLoginByPhone : BRLoginByEmail;
}

- (void)policyClick:(NSInteger)type {
    [self.view endEditing:YES];
    
    // 使用新的协议URL生成方法，根据当前语言动态生成
    NSString *url = [BRTools br_agreementURLWithType:type];
    NSString *titleStr = Localized(@"set_terms");
    if (type == 1) {
        titleStr = Localized(@"set_privacy");
    }
    GXJWebViewController *webView = [[GXJWebViewController alloc] init];
    webView.url = url ;
    [webView initWhiteBarWithTitle:titleStr isBack: YES];
    webView.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:webView animated:YES completion:nil];
}


- (void)clickLoginByFaceID {
    
    WS(weakSelf);
    [GGFaceIdManManage  gg_runFaceAction:^{
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [weakSelf requestInFace];
        }];
    } faile:^(NSInteger code) {
        if (@available(iOS 11.0, *)) { //多次失败后锁定
            if (code == LAErrorBiometryLockout) {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    [weakSelf.welcomeVC br_hiddenBiomeBtn];
                }];
            }
        }
    }];
}

- (void)didAppleIDBtnClicked API_AVAILABLE(ios(13.0)){
    
    
    ASAuthorizationAppleIDProvider *provider = [[ASAuthorizationAppleIDProvider alloc] init];
    ASAuthorizationAppleIDRequest *request = [provider createRequest];
//    request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];

    ASAuthorizationController *vc = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
    vc.delegate = self;
    vc.presentationContextProvider = self;
    [vc performRequests];
    
}

- (void)didGoogleBtnClick {
    
    FIROptions *options = [FIRApp defaultApp].options;
    
    NSString *cleiID = options.clientID;
    GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:cleiID];
    [GIDSignIn sharedInstance].configuration = config;
    
    [BRHud showInView:self.view];
    WS(weakSelf);
    [[GIDSignIn sharedInstance] signInWithPresentingViewController:self completion:^(GIDSignInResult * _Nullable signInResult, NSError * _Nullable error) {
        
        [BRHud hiddenInView:self.view];
        if (error) {
            
            NSLog(@"Google SignIn error[%@][%ld]",error.localizedDescription,error.code);
            
            return;
        }
        
        GIDGoogleUser *user = signInResult.user;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[self longinParams]];
        dic[@"type"] = @"google";
        dic[@"loginMsg"] = user.userID;
        dic[@"loginType"] = @2;
      
        if (user.profile.name.length != 0) {
            dic[@"name"] = user.profile.name;
        }
        if (user.profile.email.length != 0){
            dic[@"email"] = user.profile.email;
        }
        
        [BRUserManager share].loginType = 2;
        
        [weakSelf loginRequet:dic];
        
    }];

}

- (void)showWelcomeView {
    
    [self.welcomeVC br_show];
    
    
}


- (void)loginClick:(NSInteger)index {
   
    switch (index) {
        case 0:{
            self.titleL.text = Localized(@"login_withPhone");
            self.loginStatus = BRLogin_phone;
            [self clickLoginStatus:index];
            break;
        }
        // 暂时注释掉其他登录方式，只保留手机号登录
        /*
        case 1:{
            self.titleL.text = Localized(@"login_withEmail");
            self.loginStatus = BRLogin_Email;
            [self clickLoginStatus:index];
            break;
        }
        case 2:{
            [self didGoogleBtnClick];
            break;
        }
        case 3:{
            if (@available(iOS 13.0, *)) {
                [self didAppleIDBtnClicked];
            } 
            break;
        }
        case 4:{
            [self clickLoginByFaceID];
            break;
        }
        */
        default:
            break;
    }
    
    
}



#pragma mark - 监听
- (void)notificationDoit {
    
    if ([BrezzeTimeManage getimeIntervalBy:BRLoginByPhone wirhMax:kTimeMax] > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.loginStatus == BRLogin_phone) {
                [self startTimeStr];
            }
        });
    }else{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (self.loginStatus == BRLogin_phone) {
                [self removeTime];
            }
        });
    }
    
    // 暂时注释掉邮箱登录的定时器监听
    /*
    if ([BrezzeTimeManage getimeIntervalBy:BRLoginByEmail wirhMax:kTimeMax] > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.loginStatus == BRLogin_Email) {
                [self startTimeStr];
            }
        });
    }else{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (self.loginStatus == BRLogin_Email) {
                [self removeTime];
            }
            
            
        });
    }
    */
    
}

- (void)startTimeStr {
    _otpBtn.enabled = NO;
    NSInteger num = [BrezzeTimeManage getimeIntervalBy:self.otpTimeKey wirhMax:kTimeMax];
    NSString *str2 = [NSString stringWithFormat:@"%02lds",(long)num];
    [self->_otpBtn setTitle:str2 forState:(UIControlStateNormal)];
}

- (void)removeTime {
    
    self->_otpBtn.enabled = YES;
    
    [self->_otpBtn setTitle:Localized(@"login_get") forState:(UIControlStateNormal)];
    [BrezzeTimeManage removeObjectKey:self.otpTimeKey];
}

#pragma mark - TextField Delegate --
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason {
    
    NSLog(@"textFieldDidEndEditing = %@",textField.text);
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    NSLog(@"textFieldShouldEndEditing = %@",textField.text);
    
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    NSLog(@"textFieldShouldBeginEditing = %@",textField.text);
    
    return YES;
}

- (void)textFieldDidChangeSelection:(UITextField *)textField {
    if (textField == _OtpTF) {
        // 支持4位或6位验证码，输入完成后自动收起键盘
        if (textField.text.length == 4 || textField.text.length == 6) {
            [textField resignFirstResponder];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField != _emailTF) {
        return YES;
    }
    return [BRTools canInputText:string hasEmail:YES];
}

#pragma mark - ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller  API_AVAILABLE(ios(13.0)){
    
    return self.view.window;
}

#pragma mark - ASAuthorizationControllerDelegate

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization  API_AVAILABLE(ios(13.0)){
    
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]])       {
        ASAuthorizationAppleIDCredential *credential = (ASAuthorizationAppleIDCredential *)authorization.credential;
        
        NSString *state = credential.state;
        NSString *userID = credential.user;
        NSPersonNameComponents *fullName = credential.fullName;
        NSString *email = credential.email;
        NSString *authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding]; // refresh token
        NSString *identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding]; // access token
        ASUserDetectionStatus realUserStatus = credential.realUserStatus;
        
        NSLog(@"state: %@", state);
        NSLog(@"userID: %@", userID);
        NSLog(@"fullName: %@", fullName);
        NSLog(@"email: %@", email);
        NSLog(@"authorizationCode: %@", authorizationCode);
        NSLog(@"identityToken: %@", identityToken);
        NSLog(@"realUserStatus: %@", @(realUserStatus));
        
        NSString *name = @"";
        if (fullName.familyName.length>0) {
            name = fullName.familyName;
        }
        if (fullName.middleName.length>0) {
            name = [NSString stringWithFormat:@"%@ %@",name,fullName.middleName];
        }
        if (fullName.givenName.length>0) {
            name = [NSString stringWithFormat:@"%@ %@",name,fullName.givenName];
        }
        
//        __weak __typeof__(self) weakSelf = self;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[self longinParams]];
        dic[@"type"] = @"apple";
        dic[@"loginMsg"] = userID;
        dic[@"loginType"] = @3;
        if (name.length > 0) {
            dic[@"name"] = name;
        }
        if (email.length>0){
            dic[@"email"] = email;
        }
        [BRUserManager share].loginType = 3;
        
        [self loginRequet:dic];
        
    }
}

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error  API_AVAILABLE(ios(13.0)){
    
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
    }
    NSLog(@"%@", errorMsg);
}

#pragma mark - SET UI --
- (void)setUI {
    //UIColorMake(60, 144, 255)
    self.view.backgroundColor = UIColorWhite;
    UIColor *placeholderColor = UIColorText5;
    UIColor *textInputC = UIColorText1;
    
    
    QMUIButton *back = [[QMUIButton alloc] init];
    [back setImage:UIImageMake(@"arrow_left_LBlue44") forState:UIControlStateNormal];
    [self.view addSubview:back];
    [back mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.top.offset(KStatusBarHeight + 4);
        make.width.height.mas_equalTo(44);
    }];
    [back addTarget:self action:@selector(showWelcomeView) forControlEvents:UIControlEventTouchUpInside];
    
    self.titleL = [BRToolsView br_label:Localized(@"login_withPhone") textColor:kColorMain font:[UIFont br_fontB:28] textAlignment:NSTextAlignmentCenter];
    self.titleL.numberOfLines = 0;
    [self.view addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.right.offset(-28);
        make.top.offset(kSafeAreaTopHeight + 16);
    }];
    CGFloat btnW = (kScreenWidth - 56) / 2;
   
    
    // 暂时注释掉邮箱输入框，只保留手机号登录
    /*
    QMUITextField *emailTf = [[QMUITextField alloc] init];
    emailTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    emailTf.clearButtonPositionAdjustment = UIOffsetMake(-20, 0);
    emailTf.textInsets = UIEdgeInsetsMake(0, 28, 0, 40);
    emailTf.placeholderColor = placeholderColor;
    emailTf.font  = [UIFont br_fontM:14];
    emailTf.textColor =  textInputC;
    emailTf.tintColor = kColorMain;
    emailTf.placeholder = Localized(@"login_email");
    emailTf.delegate = self;
    [self.view addSubview:emailTf];
    emailTf.layer.cornerRadius = 14;
    emailTf.backgroundColor = kColorBGF0;
    [emailTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 56);
        make.height.mas_equalTo(56);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.titleL.mas_bottom).offset(44);
    }];
    */
        
    QMUITextField *phoneTf = [[QMUITextField alloc] init];
    phoneTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneTf.clearButtonPositionAdjustment = UIOffsetMake(-20, 0);
    phoneTf.textInsets = UIEdgeInsetsMake(0, 110, 0, 20);
    phoneTf.placeholderColor = placeholderColor;
    phoneTf.minimumFontSize = 10;
    phoneTf.adjustsFontSizeToFitWidth = YES;
    phoneTf.textColor =  textInputC;
    phoneTf.tintColor = kColorMain;
    phoneTf.font  = [UIFont br_fontM:14];
    phoneTf.placeholder = Localized(@"login_phoeNumber");
    [self.view addSubview:phoneTf];
    phoneTf.layer.cornerRadius = 14;
    phoneTf.backgroundColor = kColorBGF0;
    [phoneTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 56);
        make.height.mas_equalTo(56);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.titleL.mas_bottom).offset(44);
    }];
    phoneTf.maximumTextLength = 15;
    phoneTf.keyboardType = UIKeyboardTypePhonePad;
    
//    UIImageMake(@"login_ic_more")
    QMUIButton *areaBtn = [[QMUIButton alloc] qmui_initWithImage:UIImageMake(@"login_ic_more") title:kAddCountryCode];
    areaBtn.imagePosition = QMUIButtonImagePositionRight;
    areaBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 0);
    [areaBtn setTitleColor:textInputC forState:UIControlStateNormal];
    areaBtn.titleLabel.font = [UIFont br_fontM:14];
    [phoneTf addSubview:areaBtn];
    [areaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(phoneTf);
        make.left.equalTo(phoneTf).offset(8);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(88);
    }];
    [areaBtn addTarget:self action:@selector(getAreaNum) forControlEvents:UIControlEventTouchUpInside];
    
    QMUITextField *otpTf = [[QMUITextField alloc] init];
    otpTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    otpTf.clearButtonPositionAdjustment = UIOffsetMake(-100, 0);
    otpTf.textInsets = UIEdgeInsetsMake(0, 28, 0, 110);
    otpTf.placeholder = Localized(@"login_verificationCode");
    otpTf.placeholderColor = placeholderColor;
    otpTf.font = [UIFont fontM:14];
    [self.view addSubview:otpTf];
    otpTf.layer.cornerRadius = 14;
    otpTf.textColor =  textInputC;
    otpTf.tintColor = kColorMain;
    otpTf.backgroundColor = kColorBGF0;
    [otpTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 56);
        make.height.mas_equalTo(56);
        make.centerX.equalTo(self.view);
        make.top.equalTo(phoneTf.mas_bottom).offset(16);
    }];
    otpTf.maximumTextLength = 6;
    otpTf.keyboardType = UIKeyboardTypePhonePad;
    
    QMUIButton *otpBtn = [[QMUIButton alloc] init];
    [otpBtn setTitle:Localized(@"login_get") forState:UIControlStateNormal];
    [otpBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [otpBtn setTitleColor:UIColor.whiteColor forState:UIControlStateDisabled];
    [otpBtn setBackgroundColor:kColorMain];
    otpBtn.titleLabel.font = [UIFont fontS:12];
    otpBtn.layer.cornerRadius = 6;
    otpBtn.layer.masksToBounds = YES;
    [otpTf addSubview:otpBtn];
    [otpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(otpTf);
        make.right.equalTo(otpTf).offset(-8);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(88);
    }];
    [otpBtn addTarget:self action:@selector(sendOtpClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 暂时注释掉邮箱输入框相关代码
    // _emailTF.hidden = YES;
    _phoneTF = phoneTf;
    // _emailTF = emailTf;
    _OtpTF = otpTf;
    _phoneTF.delegate = self;
    _OtpTF.delegate = self;
    _otpBtn = otpBtn;
    _areaBtn = areaBtn;
    
    
    // 自动填充上次登录信息
    BOOL hasPhone = [BRUserManager share].loginPhone.length != 0;
    BOOL hasCode = [BRUserManager share].loginCode.length != 0;
    
    if (hasCode) {
        [areaBtn setTitle:[NSString stringWithFormat:@"+%@",[BRUserManager share].loginCode] forState:UIControlStateNormal];
        NSLog(@"📱 自动填充区号: +%@", [BRUserManager share].loginCode);
    }
    
    if (hasPhone) {
        phoneTf.text = [BRUserManager share].loginPhone;
        NSLog(@"📱 自动填充手机号: %@", [BRUserManager share].loginPhone);
        
        // 如果手机号已填充，自动聚焦到验证码输入框
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [otpTf becomeFirstResponder];
        });
    }
    
    QMUIButton *nextBtn = [[QMUIButton alloc] init];
    [nextBtn setTitle:Localized(@"login_login") forState:UIControlStateNormal];
    [nextBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [nextBtn setTitleColor:kColorTitleWhite forState:UIControlStateDisabled];
    [nextBtn setBackgroundColor:kColorMain];
    nextBtn.titleLabel.font = [UIFont fontB:17];
    nextBtn.layer.cornerRadius = 14;
    nextBtn.layer.masksToBounds = YES;
    [self.view addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.right.offset(-28);
        make.height.mas_equalTo(52);
        make.top.equalTo(otpTf.mas_bottom).offset(88);
    }];
    
    [nextBtn addTarget:self action:@selector(longin) forControlEvents:UIControlEventTouchUpInside];

    
    self.welcomeVC = [[BRWelcomeVC alloc] init];
    [self addChildViewController:self.welcomeVC ];
    [self.view addSubview:self.welcomeVC .view];
    [self.welcomeVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    WS(weakSelf);
    self.welcomeVC.loginClickBlock = ^(NSInteger index) {
        [weakSelf loginClick:index];
    };
}




- (BOOL)preferredNavigationBarHidden {
    return YES;
}

- (UIStatusBarStyle)qmui_preferredStatusBarStyle {
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleDarkContent;
    } else {
        // Fallback on earlier versions
        return UIStatusBarStyleDefault;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
